﻿/*********************************************************

    Copyright (c) Microsoft. All rights reserved.
    This code is licensed under the Microsoft Public License.
    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

*********************************************************/
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using SL_OData_Explorer.Utilities;
using OData.Silverlight;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.IO.IsolatedStorage;

namespace SL_OData_Explorer.Windows
{
    public partial class NewWorkspacePrompt : ChildWindow
    {
        MetadataUtility metadataUtility;
        ODataWorkspaceInput workspace;
        BusyIndicatorViewModel busyViewModel;

        public NewWorkspacePrompt()
        {
            InitializeComponent();

            busyViewModel = this.Resources["busyIndicatorModel"] as BusyIndicatorViewModel;
            workspace = new ODataWorkspaceInput();
            SetupCancelButton();
        }

        private void SetupCancelButton()
        {
            spInput.DataContext = workspace;
            if (App.MDViewModel.Workspaces.Count == 0)
            {
                CancelButton.IsHitTestVisible = false;
                CancelButton.Opacity = 0;
                //CancelButton.Visibility = System.Windows.Visibility.Collapsed;
            }
            metadataUtility = new MetadataUtility();
            metadataUtility.ParseComplete += new MetadataUtility.ParseCompleteDelegate(metadataUtility_ParseComplete);
        }
        bool AddToWorkspaceList = true;
        public NewWorkspacePrompt(ODataWorkspaceInput inputModel)
        {
            InitializeComponent();
            busyViewModel = this.Resources["busyIndicatorModel"] as BusyIndicatorViewModel;
            workspace = inputModel;
            SetupCancelButton();
            AddToWorkspaceList = false;
            Dispatcher.BeginInvoke(
                () =>
                {
                    DownloadMetadata(null, null);
                });
        }

        void metadataUtility_ParseComplete(EDMModel model, Exception Error)
        {
            busyViewModel.IsBusy = false;
            if (Error == null)
            {
                if (IsolatedStorageFile.IsEnabled && AddToWorkspaceList)
                {
                    IsolatedStorageUtility.AddWorkspaceToStorage(workspace.WorkspaceName, workspace.DataServiceUri);
                }
                this.Model = model;
                this.DialogResult = true;
            }
            else
            {
                UIUtility.ShowMessageBox<UseInformation>(Error.GetBaseException().Message);
            }
        }

        public string DataServiceUri;
        public EDMModel Model { get; set; }

        void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        void DownloadMetadata(object sender, RoutedEventArgs e)
        {
            ValidateInput();
            if (!validationSummary.HasErrors)
            {
                busyViewModel.BusyMessage = "Downloading Service Document,Metadata";
                busyViewModel.IsBusy = true;
                metadataUtility.StartMetadataProcessing(txtDataServiceUri.Text, txtWorkspaceName.Text);
            }
        }
        private void ValidateInput()
        {
            txtDataServiceUri.UpdateBindingSource(TextBox.TextProperty);
            txtWorkspaceName.UpdateBindingSource(TextBox.TextProperty);
        }

        private void txtDataServiceUri_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                DownloadMetadata(sender, e);
            }
        }

        private void hlInputDataService_Click(object sender, RoutedEventArgs e)
        {
            workspace.DataServiceUri = "http://services.odata.org/Northwind/Northwind.svc/";
        }
    }


    public class ODataWorkspaceInput : INotifyPropertyChanged
    {
        private string _workspaceName;
        private string _dataServiceUri;
        [Required(AllowEmptyStrings = false, ErrorMessage = "Workspace name should not be empty")]
        public string WorkspaceName
        {
            get
            {
                return _workspaceName;
            }
            set
            {
                var ctx = new ValidationContext(this, null, null) { MemberName = "WorkspaceName" };
                Validator.ValidateProperty(value, ctx);
                _workspaceName = value;
                RaisePropertyChanged("WorkspaceName");
            }
        }


        [Required(AllowEmptyStrings = false, ErrorMessage = "Data Service Uri should not be empty")]
        public string DataServiceUri
        {
            get
            {
                return _dataServiceUri;
            }
            set
            {
                var ctx = new ValidationContext(this, null, null) { MemberName = "DataServiceUri" };
                Validator.ValidateProperty(value, ctx);
                if (!Uri.IsWellFormedUriString(value, UriKind.Absolute))
                {
                    throw new ValidationException("Data Service Uri is not a valid Uri string");
                }
                _dataServiceUri = value;
                RaisePropertyChanged("DataServiceUri");
            }
        }

        private void RaisePropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }


}

